package ar.com.photo_admin.service

;import org.codehaus.groovy.grails.web.mapping.LinkGenerator;

import ar.com.photo_admin.domain.*;
import grails.converters.*;

class UserService {

	static transactional = true
	
	def eventService
	
	def eventAlbumService
	
	LinkGenerator grailsLinkGenerator
	
    def save(User user) {
		return user.save(flush : true)
    }
	
	def findByUsernameOrEmail(String userId) {
		return userId?.contains("@") ? User.findByEmail(userId) : User.findByUsername(userId)
	}	
	
	/**
	 * If the user has related albums, those photos are returned. Otherwise, presentation photos of any photographer in the system are used.
	 * 
	 * @param userId
	 * @return urls
	 */
	Set getPresentationPhotosUrls(userId) {
		
		User user = User.get(userId)
		Set albums = eventAlbumService.getAlbums()
		
		Set presentationLinks = []			
		
		
		albums.each { album ->		
			def albumUrl = grailsLinkGenerator.link(controller: 'eventAlbum', action: 'show', id: album.id);
			// Nos quedamos solo aquellas que no son verticales						
			album.photoInAlbums.findAll{ it.photo.height < it.photo.width }.each { photoInAlbum ->				
				presentationLinks.add( new PresentationLink(photoUrl: photoInAlbum.photo.getPublishedUrl(), albumUrl:albumUrl));
			}
		} 
		
			
		
		if ( presentationLinks.size()==0 ) {
			Photographer.findAll().each { photographer ->	
				photographer.presentationPhotos.each { photo ->
					presentationLinks.add( new PresentationLink(photoUrl: photo.url, albumUrl:"#"));
				}
							
				
			}
		}
	
		return presentationLinks
	}
	
	def loadUserFromAutocompleteText(def autocompleteText){
		def textParts = autocompleteText.split("-");
		return textParts.size()>1 ? findByUsernameOrEmail(textParts[1].trim()) : findByUsernameOrEmail(autocompleteText);
	}
	
	def autocompleteUser(term){
		def c = User.createCriteria()
		
		def users = c.list {
			or {
				like("username", term + '%')
				like("email", term + '%')
			}
		}
		
		def res = []
		users.each { user -> res << autocompleteUserToString(user) }
		
		return (res as JSON)
	}
	
	def autocompleteUserToString(user){
		def value = user.username + " - " + user.email 
		return value  	
	}
		
}
